//
//  KindVC.m
//  MyTest
//
//  Created by zhiyou on 16-4-18.
//  Copyright (c) 2016年 wangyang. All rights reserved.
//

#import "KindVC.h"
#import "KindCell.h"
#import "FirstCell.h"
#import "GoodsCell.h"
#import "DongTai.h"

#define BASE_BASKETBALL @"http://www.shihuo.cn/app_swoole_zone/home?platform=ios&timestamp=1460367958&v=4.0.2&token=09a9b99e309dba33266c750e84ca3613&type=basketball"
#define BASE_RUNNING @"http://www.shihuo.cn/app_swoole_zone/home?platform=ios&timestamp=1460376416&v=4.0.2&token=e5cdfab25efd759f6c707a14edcb5125&type=running"
#define BASE_FREESTYLE @"http://www.shihuo.cn/app_swoole_zone/home?platform=ios&timestamp=1460376622&v=4.0.2&token=b27af7165f8e09638b98392067a34b8c&type=freestyle"
#define BASE_BASKETBALL_1 @"http://www.shihuo.cn/app_swoole_zone/getNews?platform=ios&timestamp=1460367958&v=4.0.2&token=d1a5fcfa50addf4788875b588156eacb&page_size=20&type=basketball&page="
#define BASE_RUNNING_1 @"http://www.shihuo.cn/app_swoole_zone/getNews?platform=ios&timestamp=1460376416&v=4.0.2&token=8fd54cf1eb0a23b3d78b93442bae3969&page_size=20&type=running&page="
#define BASE_FREESTYLE_1 @"http://www.shihuo.cn/app_swoole_zone/getNews?platform=ios&timestamp=1460376622&v=4.0.2&token=b6b5d9017b3f3e5efc5cd6a558e6a202&page_size=20&type=freestyle&page="

@interface KindVC ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UILabel *titleLab;

@property (nonatomic, strong) NSArray *topArr;
@property (nonatomic, strong) NSArray *bottomArr;

@property (nonatomic, strong) NSMutableArray *bannerArr;
@property (nonatomic, strong) NSMutableArray *categoryArr;
@property (nonatomic, strong) NSMutableArray *topicArr;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UIView *bgView;
@end

@implementation KindVC
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    _topArr = [[NSArray alloc] initWithObjects:BASE_BASKETBALL,BASE_RUNNING,BASE_FREESTYLE, nil];
    _bottomArr = [[NSArray alloc] initWithObjects:BASE_BASKETBALL_1,BASE_RUNNING_1,BASE_FREESTYLE_1, nil];
    _dataArr = [[NSMutableArray alloc] init];
    [self setBar];
    [self getData];
    
    NSString *URL = _bottomArr[_index-100];
    NSString *url = [NSString stringWithFormat:@"%@%d",URL,1];
    [self getDataArrWithURL:url];
    
}
#pragma mark -- 初始化tableView
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, Width, Height-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerClass:[GoodsCell class] forCellReuseIdentifier:@"GoodsCell"];
        [_tableView registerClass:[KindCell class] forCellReuseIdentifier:@"KindCell"];
        self.tableView.tableHeaderView = [self headerView];
    }
    [self refresh];
    return _tableView;
}
#pragma mark -- UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else
    {
        return _dataArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        KindCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KindCell" forIndexPath:indexPath];
        cell.contentView.backgroundColor = [UIColor grayColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        Zone *zone1 = _topicArr[0];
        cell.titleLabel1.text = zone1.title;
        cell.subTitleLable1.text = zone1.sub_title;
        [cell.imgView1 sd_setImageWithURL:[NSURL URLWithString:zone1.img_url]];

        Zone *zone2 = _topicArr[1];
        cell.titleLabel2.text = zone2.title;
        cell.subTitleLable2.text = zone2.sub_title;
        [cell.imgView2 sd_setImageWithURL:[NSURL URLWithString:zone2.img_url]];

        Zone *zone3 = _topicArr[2];
        cell.titleLabel3.text = zone3.title;
        cell.subTitleLable3.text = zone3.sub_title;
        [cell.imgView3 sd_setImageWithURL:[NSURL URLWithString:zone3.img_url]];
        
        Zone *zone4 = _topicArr[3];
        cell.titleLabel4.text = zone4.title;
        cell.subTitleLable4.text = zone4.sub_title;
        [cell.imgView4 sd_setImageWithURL:[NSURL URLWithString:zone4.img_url]];

        return cell;
    }else
    {
        GoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        DongTai *dongTai = _dataArr[indexPath.row];
        cell.dongTai = dongTai;
        return cell;

    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 150;
    }else
    {
        return 100;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
#pragma mark -- 创建表头
- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4+60)];
    
    for (int i = 0; i < _categoryArr.count; i++) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(Width*i/_categoryArr.count, Height/4, Width/_categoryArr.count, 60)];
        bgView.tag = i;
        [headerView addSubview:bgView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
        [bgView addGestureRecognizer:tap];
        
        Find *find = _categoryArr[i];
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [imgView sd_setImageWithURL:[NSURL URLWithString:find.img_url]];
        [bgView addSubview:imgView];
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(bgView.mas_centerX);
            make.top.equalTo(bgView.mas_top).offset(5);
            make.width.height.equalTo(bgView.mas_height).multipliedBy(.6);
        }];
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.font = [UIFont systemFontOfSize:11];
        titleLab.text = find.name;
        [bgView addSubview:titleLab];
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(bgView.mas_centerX);
            make.top.equalTo(imgView.mas_bottom).offset(5);
        }];
        
        
    }
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Width, Height/4)];
    _scrollView.tag = 2000;
    for (int i = 0; i < _bannerArr.count; i++) {
        
        // 图片坐标从0开始
        UIImageView * imageView=  [[UIImageView alloc] initWithFrame:CGRectMake(Width*i, 0, Width, Height/4)];
        Banner *banner = _bannerArr[i];
        NSString *urlStr = [NSString stringWithFormat:@"%@",banner.img_url];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        imageView.image = image;
        imageView.tag = 1000+i;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToNext:)];
        tap.numberOfTapsRequired = 1;
        [imageView addGestureRecognizer:tap];
        
        [_scrollView addSubview:imageView];
    }
    _scrollView.contentSize = CGSizeMake(Width * _bannerArr.count, 120);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    _scrollView.delegate = self;
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, Height/4-20, Width, 20)];
    _pageControl.numberOfPages = _bannerArr.count;
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    [_pageControl addTarget:self action:@selector(pageControlChanged) forControlEvents:UIControlEventValueChanged];
    
    [headerView addSubview:_scrollView];
    [headerView addSubview:_pageControl];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    
    return headerView;
}
- (void)pageControlChanged
{
    [_scrollView setContentOffset:CGPointMake(_pageControl.currentPage *Width, 0) animated:YES];
    [_timer invalidate];
    _timer = nil;
}

- (void)changeImage
{
    // 定义一个静态变量,代表方向
    static int direction = 1;
    if (_scrollView.contentOffset.x == 0)
    {
        direction = 1;
    }
    if (_scrollView.contentOffset.x == Width*(_bannerArr.count-1))
    {
        direction = -1;
    }
    // 设置滚动视图的偏移量,带动画
    [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x+Width*direction, 0) animated:YES];
}

#pragma mark -- UIScrollViewDelegate
// 将要开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 开始拖拽时,把定时器关闭
    [_timer invalidate];
    _timer = nil;
}

//已经结束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
}

// 将要开始减速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    
}

// 已经结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
    // 结束减速把定时器重新开启
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_timer == nil)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
    }
    
    float offSet_x = scrollView.contentOffset.x;
    _pageControl.currentPage = offSet_x/Width;
}
- (void)goToNext:(UIGestureRecognizer *)tap
{
    
}
- (void)tapView:(UITapGestureRecognizer *)tap
{
    UIView *imgView = [tap view];
    NSLog(@"%ld",(long)imgView.tag);
}
#pragma mark -- 获取请求数据
- (void)getData
{
    [MyRequest getWithURL:_topArr[_index-100] parameters:nil success:^(NSDictionary *dic) {
        NSDictionary *dictionary = [dic objectForKey:@"data"];
        
        NSArray *arr1 = [dictionary objectForKey:@"banner"];
        self.bannerArr = [MyTools getBannerWithArray:arr1];
        
        NSArray *arr2 = [dictionary objectForKey:@"category"];
        self.categoryArr = [MyTools getFindWithArr:arr2];
        
        NSArray *arr3 = [dictionary objectForKey:@"topic"];
        self.topicArr = [MyTools getZoneWithArray:arr3];
        
        [self.view addSubview:self.tableView];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
- (void)getDataArrWithURL:(NSString *)URL
{
    [MyRequest getWithURL:URL parameters:nil success:^(NSDictionary *dic) {
        NSArray *arr = [dic objectForKey:@"data"];
        for (NSDictionary *dic in arr) {
            DongTai *dongTai = [[DongTai alloc] initWithDictionary:dic];
            [_dataArr addObject:dongTai];
        }
        [_tableView reloadData];
    } fail:^(NSError *error) {
        NSLog(@">>>>%@",error);
    }];
}
#pragma mark -- 创建导航
- (void)setBar
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 64)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:bgView.frame];
    imageView.image = [UIImage imageNamed:@"topbar"];
    [bgView addSubview:imageView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 20, 50, 40);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"F_iocn_normal"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:backBtn];
    
    UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtn.frame = CGRectZero;
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"D_iocn_normal"] forState:UIControlStateNormal];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:menuBtn];
    
    [menuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView.mas_top).offset(20);
        make.right.offset(-10);
        make.width.offset(50);
        make.height.offset(40);
    }];
    
    _titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLab.text = self.title;
    _titleLab.font = [UIFont systemFontOfSize:20];
    [bgView addSubview:_titleLab];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView.mas_centerX);
        make.centerY.equalTo(bgView.mas_centerY).offset(10);
    }];
}
#pragma mark -- 刷新加载
- (void)refresh
{
    __block KindVC *mySelf = self;
    
    [_tableView addPullToRefreshWithActionHandler:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [mySelf.tableView.pullToRefreshView stopAnimating];
            [mySelf getData];
        });
    }];
    
    [_tableView addInfiniteScrollingWithActionHandler:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [mySelf.tableView.infiniteScrollingView stopAnimating];
            static int count = 2;
            [mySelf getDataArrWithURL:[NSString stringWithFormat:@"%@%d",mySelf.bottomArr[mySelf.index-100],count]];
            count ++;
        });
    }];
}

- (void)showMenu
{
    static int count = 1;
    if (count%2 == 1) {
        
        [self setMenu];
    }else
    {
        [self hideView];
    }
    count ++;
}
- (void)setMenu
{
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(Width*2/3, 64, Width/3, 90)];
    _bgView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_bgView];
    
    NSArray *arr = @[@"首页",@"我的",@"消息"];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 30*i, Width/3, 30);
        button.tag = i;
        [button setTitle:arr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        [_bgView addSubview:button];
        _bgView.clipsToBounds = YES;
    }
}
- (void)clickButton:(UIButton *)button
{
    
}
- (void)hideView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    _bgView.frame = CGRectMake(Width*2/3, 64, 0, 0);
    [UIView commitAnimations];
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
